package com.malou.client.ventas.cajainicial;

import java.util.Date;

import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.KeyListener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.widget.Label;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.NumberField;
import com.extjs.gxt.ui.client.widget.layout.CenterLayout;
import com.extjs.gxt.ui.client.widget.layout.FormData;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.KeyCodes;
import com.malou.client.MalouConstants;

public class CajaInicialForm extends FormPanel {

	private NumberField saldoinicial;
	private Button guardar;
	private MalouConstants constants = GWT.create(MalouConstants.class);

	public CajaInicialForm() {
		setHeading("Caja Inicial");
		setSize(280, 130);
		setFrame(true);
		setLayout(new CenterLayout());
		setButtonAlign(HorizontalAlignment.CENTER);

		mask(constants.cargando());

		guardar = new Button(constants.guardar());
		guardar.hide();
		guardar.addSelectionListener(new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				guardar();
			}

		});
		addButton(guardar);

		CajaIniciales.cif = this;
		CajaIniciales.checkSaldoInicial(new Date());

	}

	public void addMessage() {
		guardar.hide();
		if (saldoinicial != null)
			remove(saldoinicial);
		unmask();
		Label lbl = new Label(constants.montoInicialIngresado());
		lbl.setStyleAttribute("fontSize", "13px");
		add(lbl);
		layout();

	}

	public void addFields() {
		unmask();
		saldoinicial = new NumberField();
		saldoinicial.setEmptyText("Ingrese monto...");
		saldoinicial.setInputStyleAttribute("textAlign", "center");
		saldoinicial.setInputStyleAttribute("fontSize", "15px");
		saldoinicial.setSize(120, 30);
		saldoinicial.setAllowBlank(false);
		saldoinicial.addListener(Events.KeyDown, new KeyListener() {
			public void componentKeyDown(ComponentEvent event) {
				if (event.getKeyCode() == KeyCodes.KEY_ENTER)
					guardar();
			}
		});
		add(saldoinicial, new FormData());
		guardar.show();

		layout();

	}
	protected boolean validate() {
		return saldoinicial.isValid();
	}

	private void guardar() {
		if (validate()) {
			CajaInicial balance = new CajaInicial();
			balance.setFecha(new Date());
			Double monto = Double.valueOf(saldoinicial.getValue().toString());
			balance.setSaldoinicial(monto);
			CajaIniciales.save(balance);
			mask(constants.guardando());
		}
	}
}
